package com.naiterui.ehp.ps.sms.factory;

import com.alibaba.fastjson.JSONObject;
import com.naiterui.ehp.ps.sms.enums.HuaxinStatus;
import com.naiterui.ehp.ps.sms.exception.ExceptionCodes;
import com.naiterui.ehp.ps.sms.exception.SmsBusinessException;
import com.naiterui.ehp.ps.sms.vo.MessageResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * @Description 华信短信平台
 * @Author gongbaoqiang
 * @Date 2020/6/15 11:46 AM
 */
@Slf4j
public class HuaxinSms {

    /**
     * 单条短信发送
     * @param phone
     * @param content
     * @return
     * @throws SmsBusinessException
     */
    public static MessageResponseVO siggleSend(String phone, String content) throws SmsBusinessException {
        // 发送短信
        String result = HuaxinApi.singleSend(phone, content);
        log.info("[发送短信，华信平台]--短信发送完成，手机号电话号码:[{}] 内容为:[{}] 第三方平台返回结果:[{}]", phone, content, result);
        MessageResponseVO messageResponseVO = processApiResult(result);
        return messageResponseVO;
    }

    /**
     * 处理API返回的结果
     * CloopenSms.processApiResult()
     *
     * @param result
     *
     * @return
     *
     * @throws SmsBusinessException
     * @Author
     * @Date 2017年7月26日
     * @since 1.0.0
     */
    private static MessageResponseVO processApiResult(String result) throws SmsBusinessException {
        // 处理api请求结果
        if (StringUtils.isEmpty(result)) {
            log.error("容联平台返回结果为空：[{}]", result);
            throw new SmsBusinessException(ExceptionCodes.SMS_PLATFORM_RETURN_NULL);
        }
        JSONObject resultJson = JSONObject.parseObject(result);
        MessageResponseVO responseVO = new MessageResponseVO();
        String returnStatus = resultJson.getString("returnstatus");
        if (HuaxinStatus.SUCCESS.msg.equals(returnStatus)) {
            responseVO.setStatusCode(String.valueOf(ExceptionCodes.SUCCESS));
            responseVO.setStatusMsg("成功");
        } else {
            responseVO.setStatusCode(String.valueOf(ExceptionCodes.SMS_PLATFORM_RETURN_ERROR));
            responseVO.setStatusMsg(resultJson.getString("message"));
        }

        return responseVO;
    }

}
